# Copyright (c) 2020 Presto Labs Pte. Ltd.
# Author: xguo, donggu

import io
import csv
import requests
from coin2.exchange.product_info import ProductInfoDefault
from coin2.exchange.symbology import SymbologyInfo


def gen_var_ticks():
  price_list = [1e9, 2000000., 1000000., 500000., 100000., 10000., 1000., 100., 10., 0]
  tick_list = [1000., 500., 100., 50., 10., 5., 1., 0.1, 0.01]

  range_list = list(zip(price_list[:-1], price_list[1:]))
  result = []
  for r, tick in zip(range_list, tick_list):
    assert r[0] > r[1]
    info = {
        'from': r[1],
        'to': r[0],
        'value': tick,
    }
    result.append([info['from'], info['to'], info['value']])
  return result


def generate():
  mea = 'Spot.Lmaxdigital.v1'
  me = 'Spot.Lmaxdigital'
  default = ProductInfoDefault()
  symbol_info = SymbologyInfo()
  # this lmax digital websocket used data, not public for user
  # data = requests.get('https://md.lmaxglobal.io/digital/instruments/depths').json()
  get = requests.get('https://www.lmaxdigital.com/documents/csv/LMAXDigital-Instruments.csv')
  assert get.status_code == requests.codes.ok, "Failed to get data from lmax digital"
  f = io.StringIO(get.text)
  reader = csv.reader(f)
  header = next(reader, None)

  pis = []
  filter_list = ["Polygon (USD)", "Chainlink (USD)"]
  for row in reader:
    info = dict(zip(header, row))
    native_symbol = info['Instrument Name']
    if native_symbol is None or native_symbol == '':
      continue
    
    if native_symbol in filter_list:
      continue

    native_base, native_quote = native_symbol.split('/')
    base = symbol_info.native_to_norm_currency(mea, native_base)
    quote = symbol_info.native_to_norm_currency(mea, native_quote)
    symbol = "%s-%s" % (base, quote)

    pi = dict(
        id=info['LMAX ID'],
        symbol=symbol,
        base=base,
        quote=quote,
        native_symbol=native_symbol,
        native_base=native_base,
        native_quote=native_quote,
        is_inverse=False,
        price_ticksize=float(info['Tick Value']),
        qty_ticksize=float(info['Min Order Size']),
    )

    pi = {**pi, **default.product_info(me, symbol)}
    pis.append(pi)

  pis = sorted(pis, key=lambda x: x['symbol'])
  return pis


if __name__ == '__main__':
  import json
  config = generate()
  print(json.dumps(config, indent=2))
